package com.atguigu.gulimall.order.config;

import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.connection.CorrelationData;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.amqp.support.converter.Jackson2JsonMessageConverter;
import org.springframework.amqp.support.converter.MessageConverter;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import javax.annotation.PostConstruct;

@Configuration
public class RabbitConfig {

    @Autowired
    RabbitTemplate rabbitTemplate;

    @Bean
    public MessageConverter messageConverter(){
        return new Jackson2JsonMessageConverter();
    }

    @PostConstruct
    public void rabbitTemplate(){
        rabbitTemplate.setConfirmCallback(new RabbitTemplate.ConfirmCallback() {

            //调用了confirm方法说明broker收到消息了
            //消息状态 0-新建 1-已发送 2-错误抵达 3-已抵达
            //应将消息表中的状态改为 1-已发送
            @Override
            public void confirm(CorrelationData correlationData, boolean ack, String msg) {
                System.out.println("correlationData:"+correlationData);
                System.out.println("ack or nack:"+ack);
                System.out.println("message:"+msg);
            }
        });

        /**
         * 注意，这个是从exchange发送到queue失败才会调用，成功则不会调用
         */
        rabbitTemplate.setReturnCallback(new RabbitTemplate.ReturnCallback() {

            //调用return方法说明出现了错误
            //应将消息表中的状态改为 2-错误抵达
            @Override
            public void returnedMessage(Message message, int replyCode, String replyText, String exchange, String routingKey) {
                System.out.println(String.format("message=>{%s},replyCode=>{%d},replyText=>{%s},exchange=>{%s},routingKey=>{%s}",
                        message, replyCode, replyText, exchange, routingKey));
            }
        });
    }

}
